package com.cool.reggie.modules.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cool.reggie.core.exception.CustomException;
import com.cool.reggie.modules.category.entity.CategoryEntity;
import com.cool.reggie.modules.category.mapper.CategoryMapper;
import com.cool.reggie.modules.category.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cool.reggie.modules.dish.entity.DishEntity;
import com.cool.reggie.modules.dish.service.DishService;
import com.cool.reggie.modules.setmeal.entity.SetmealEntity;
import com.cool.reggie.modules.setmeal.service.SetmealService;
import com.cool.reggie.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author 1950735817@qq.com
 * @since 2022-07-06
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public PageUtils queryCategoryPage(int page, int pageSize) {
        Page<CategoryEntity> pageParam = new Page<>();
        LambdaQueryWrapper<CategoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(CategoryEntity::getSort);

        Page<CategoryEntity> entityPage = categoryMapper.selectPage(pageParam, queryWrapper);
        return new PageUtils(entityPage);
    }

    @Override
    public Boolean removeCategory(Long id) {
        LambdaQueryWrapper<DishEntity> entityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        entityLambdaQueryWrapper.eq(DishEntity::getCategoryId, id);
        long count1 = dishService.count(entityLambdaQueryWrapper);
        if(count1>0){
            throw new CustomException("当前分类下关联了菜品，禁止删除");
        }

        LambdaQueryWrapper<SetmealEntity> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(SetmealEntity::getCategoryId, id);
        long count2 = setmealService.count(queryWrapper2);
        if(count2>0){
            throw new CustomException("当前分类下关联了套餐，禁止删除");
        }

        return super.removeById(id);
    }
}
